# # datetime模块
from datetime import time, date, datetime, timedelta, timezone, tzinfo
def testDatetime():
    print("当前时间：",datetime.now())
    print("当前UTC时间：",datetime.utcnow())
    print("将时间字符串转成datetime类型：",datetime.strptime('29220101','%Y%m%d'))
    print("将时间字符串转成datetime类型：",datetime.strptime('29220101122345','%Y%m%d%H%M%S'))
    print("实例化datetime对象：",datetime(2022,1,1,0,0,1,2))
    print("实例化date对象：",date(2022,1,1))
    print("实例化time对象：",time(12))
    print("实例化time对象：",time(12,0))
    print("实例化time对象：",time(12,0,0))
    print("实例化time对象：",time(1,1,1,1))
    print("修改时间：",date(2022,1,1).replace(2020,12,12))
    print("返回时间元组：",date(2022,1,1).timetuple())
    print("时间戳：",datetime(2022,1,1,0,0,1,2).timestamp())
    print("星期几(星期一为0,星期日为6)：",datetime(2022,6,11,0,0,1,2).weekday())
    print("星期几(星期一为1,星期日为7)：",datetime(2022,6,11,0,0,1,2).isoweekday())
    print("日期时间字符串：",datetime(2022,6,11,0,0,1,2).strftime('%Y-%m-%d %X'))
    print("日期和时间字符串：",datetime(2022,6,11,0,0,1,2).ctime())
    print("日期的预期格列高利历序号：",datetime(2022,6,11,0,0,1,2).toordinal())
    # timedelta类
    nowDate = datetime.now()
    print("当前时间：",nowDate)
    print("当前三天后时间：",nowDate+timedelta(days=3))
    print("当前三天一个半小时后时间：",nowDate+timedelta(days=3,hours=1.5))
    print("当前三天一小时后时间：",nowDate+timedelta(days=3,hours=1,minutes=1,seconds=1))
    print("当前三天一小时前时间：",nowDate-timedelta(days=3,hours=1,minutes=1,seconds=1))
    newYear = datetime(nowDate.year+1,1,1,0,0,0)
    delta = newYear-nowDate
    print("元旦距今日此时时间间隔：",delta)
    print("时间间隔总秒数：",delta.total_seconds())
    # datetime.date 处理日期
    todayDate = date.today()
    print("当前日期",todayDate,"当前年份",todayDate.year,"当前月份",todayDate.month,"今天日期",todayDate.day)
    print("当前年份",todayDate.__getattribute__('year'),"当前月份",todayDate.__getattribute__('month'),"今天日期",todayDate.__getattribute__('day'))
    print("变为时间戳：",todayDate.toordinal())
    print("变为时元组：",todayDate.timetuple())
    print("返回当前日期年份：",todayDate.timetuple().tm_year)
    print("获得日期的字符串：",todayDate.__str__())
    print("将日期以指定形式输出：",todayDate.strftime("%Y%m%d"))
    print("将日期以指定形式输出：",todayDate.__format__("%Y_%m_%d"))
    print("将日期以ctime样式输出：",todayDate.ctime())
    todayDate1=date(2022,6,1)
    print("日期比较：",todayDate>todayDate1)
    print("日期比较：",todayDate.__eq__(todayDate1)) # __eq__()等于，__ge__()大于等于，__gt__()大于，__le__()小于等于，__lt__()小于，__ne__()不等于
    print("时间间隔(正向)：",todayDate.__sub__(todayDate1))
    print("时间间隔(反向)：",todayDate1.__rsub__(todayDate))
    print("时间间隔天数：",todayDate.__sub__(todayDate1).days)
    print("ISO标准化日期：",todayDate.isocalendar()) # 返回一个包含三个值的元组，三个值依次为：year年份，week number周数，weekday星期数（周一为1...周日为7）
    print("ISO标准化日期：",todayDate.isocalendar()[0],todayDate.isocalendar()[1],todayDate.isocalendar()[2])
    print("ISO标准化日期：",todayDate.isoformat())
    print("ISO标准化日期：",todayDate.isoweekday()) # 指定日期所在星期数（周一为1...周日为7）
    print("日期所在星期数：",todayDate.weekday()) # 指定日期所在星期数（周一为0...周日为6）
    print("最大的年，月，日的数值：",todayDate1.max,"最小的年，月，日的数值",todayDate1.min)
    # datetime.time 处理时间
    timeDate = time(12,30,0,1)
    print("当前时间：",timeDate,"时间：",timeDate.hour,timeDate.minute,timeDate.second,timeDate.microsecond)
    print("获得时间的字符串：",timeDate.__str__())
    print("将时间以指定形式输出：",timeDate.strftime("%H:%M:%S"))
    print("将时间以指定形式输出：",timeDate.__format__("%H_%M_%S"))
    timeDate1 = time(12,0,0,1)
    print("时间比较：",timeDate>timeDate1)

def testDatetime1():
    print("实例化date对象：",date(2022,1,1))
    print("实例化time对象：",time(10,10,0))
    print("实例化datetime对象：",datetime(2020,9,1,10,10,0))
    print("实例化datetime对象：",datetime(2020,9,1,10,10,0,742535))
    print("当前时间：",datetime.today())
    print("当前时间：",datetime.now())
    print("将时间以指定形式输出：",datetime.strftime(datetime.now(),'%Y-%m-%d %H:%M:%S'))
    print("当前时间12小时前：",datetime.now() - timedelta(12/24))
    print("combine，把指定的date和time对象整合为datetime对象：",datetime.combine(date(2022,1,1),time(10,10,0)))
    now = datetime.now() # now 没有指定时区，为 naive 类型的时间
    print("当前时间时区：",now.tzinfo)
    utcnow = datetime.now(timezone.utc) # 指定 UTC 时区，为 aware 类型的时间
    print("当前时间时区：",utcnow.tzinfo)
    tz_utc_8 = timezone(timedelta(hours=8)) # 创建时区UTC+8:00，即东八区对应的时区
    dt = now.replace(tzinfo=tz_utc_8) # 强制设置为UTC+8:00
    print("时区时间：",dt,"时间时区：",dt.tzinfo)

    d = date(2022,1,1)
    print(d)
    print('year:', d.year,'month:', d.month,'day:', d.day)
    d =datetime.combine(date(2022,1,1),time(10,10,0))
    print(d)
    print('year:', d.year,'month:', d.month,'day:', d.day)
    print('hour',d.hour,'minute',d.minute,'second',d.second)

    t = time(22, 45, 59, 1)
    print(t)
    print('hour:', t.hour,'minute:', t.minute,'second:', t.second)
    print('microsecond:', t.microsecond) #微秒
    print('格式化输出：', t.strftime('%H:%M:%S'))
    print('Earliest  :', datetime.min) 
    print('Latest    :', datetime.max)
    print('Earliest  :', time.min) 
    print('Latest    :', time.max) 

    d = date(2022,1,1)
    # Timedelta对象表示一段持续时间，所以，我们可以用它们来计算两个日期或时间之间的差值
    # 以周、天、小时、分、秒和微秒为单位创建timedelta对象。以天和小时-分钟-秒的组合形式输出
    timedel=timedelta(days=4)
    print('1999-12-31四天后的日期是：', d+timedel)
    timedel=timedelta(days=-4)
    print('1999-12-31四天前的日期是：', d+timedel)
    # ctime，它能以更详细或扩展的格式来返回日期信息。
    print("ctime，以更详细或扩展的格式来返回日期信息：",d.ctime())

def utcTime():
    utc_now= datetime.now(tz=BJinfo())
    print("当前时间时区：",utc_now)
    print("当前时间时区格式化：",datetime.strftime(utc_now,'%Y-%m-%d %H:%M:%S %Z'))

    # 指定utc时区，0时区
    utc_now = datetime.utcnow().replace(tzinfo=timezone.utc)
    print(utc_now)
    # 通过astimezone切换到东八区
    beijing = utc_now.astimezone(timezone(timedelta(hours=8)))
    print(beijing)
    # UTC时区切换到东九区：东京时间
    tokyo = utc_now.astimezone(timezone(timedelta(hours=9)))
    print(tokyo)
    # 北京时间（东八区）直接切换到东京时间（东九区）
    tokyo_new = beijing.astimezone(timezone(timedelta(hours=9)))
    print(tokyo_new)
    
# 东八区时区类
class BJinfo(tzinfo):
    """BJinfo"""
    def utcoffset(self, dt):
        return timedelta(hours=8)

    def tzname(self, dt):
        return "UTC 8"

    def dst(self, dt):
        return timedelta(hours=8)

def testDatetime2():
    today = date.today()
    print("当前日期：",today)  # 当前日期
    print("当前日期(字符串)：",today.ctime())   # 返回日期的字符串
    print("时间元组信息：",today.timetuple())   # 当前日期的时间元组信息
    print("年：",today.year)   # 返回today对象的年份
    print("月：",today.month)  # 返回today对象的月份
    print("日：",today.day)   # 返回today对象的日
    print("星期：",today.weekday())  # 0代表星期一，类推
    print("公历序数：",today.toordinal())  # 返回公历日期的序数
    print("年/周数/星期：",today.isocalendar())   # 返回一个元组：一年中的第几周，星期几

    today = date.today()
    # 2020-12-26  默认连接符号是-
    print(today)
    # 2020/12/26 指定连接符 /
    print(today.strftime("%Y/%m/%d"))
    # 2020:12:26 指定连接符 :
    print(today.strftime("%Y:%m:%d"))
    # 2020/12/26 00:00:00 转化为具体的时间
    print(today.strftime("%Y/%m/%d %H:%M:%S"))

    print(datetime.today())
    print(datetime.now())
    print(datetime.utcnow())# 返回当前UTC日期和时间的datetime对象
    print(datetime.fromtimestamp(1697302830))  # 时间戳的datetime对象
    print(datetime.fromordinal(699000) )
    print(datetime.combine(date(2020,12,25), time(11,22,54)))  # 拼接日期和时间
    print(datetime.strptime("2020-12-25","%Y-%m-%d"))

    d = datetime(2020,12,25,11,24,23)
    print(d.date())
    print(d.time())
    print(d.timetz())  # 从datetime中拆分出具体时区属性的time
    print(d.replace(year=2021,month=1))  # 替换
    print(d.timetuple())  # 时间元组
    print(d.toordinal())  # 和date.toordinal一样
    print(d.weekday())
    print(d.isoweekday())
    print(d.isocalendar())
    print(d.isoformat())
    print(d.strftime("%Y-%m-%d :%H:%M:%S"))

if __name__ == "__main__":
    testDatetime()
    print("============ 分割线 ============")
    testDatetime1()
    print("============ 分割线 ============")
    utcTime()
    print("============ 分割线 ============")
    testDatetime2()

    
